/**
 * 高拍仪中 websocket 的封装
 */
//定义socket对象

let WsSocketObject = window.WebSocket || window.MozWebSocket;

//默认配置对象数据
const defaultOptions = {
  //websocket 地址
  url: "ws://localhost:8181",
  //接收到数据的回调
  onMessage: () => {},
  //打开链接事件
  onOpen: () => {},
  //读取身份证
  onReadCard: () => {},
  //人证对比事件
  onWitness: () => {},
  //关闭事件
  onClose: () => {},
  //通讯错误事件
  onError: err => {
    console.error("通讯错误", err);
  },
  //扫描
  onScreen: () => {},
  //传递的数据类型
  dataType: "json"
};

//封装高拍仪对象
export function GPYWebSocket({
  url,
  onMessage,
  onOpen,
  onClose,
  onError,
  onReadCard,
  onWitness,
  dataType,
  onScreen
}) {
  console.log("defaultOptions", defaultOptions);
  let ws = new WsSocketObject(url || defaultOptions.url);
  this.ws = ws;
  this.onMessage = onMessage || defaultOptions.onMessage;
  this.onOpen = onOpen || defaultOptions.onOpen;
  this.onClose = onClose || defaultOptions.onClose;
  this.onError = onError || defaultOptions.onError;
  this.onReadCard = onReadCard || defaultOptions.onReadCard;
  this.onWitness = onWitness || defaultOptions.onWitness;
  this.openSuccessFlag = false;
  this.dataType = dataType || defaultOptions.dataType;
  this.onScreen = onScreen || defaultOptions.onScreen;

  //初始化socket对象
  SocketInit(this);
}

export function base64ToFile(urlData, fileName) {
  let arr = urlData.split(",");
  // let mime = arr[0].match(/:(.*?);/)[1];
  let bytes = atob(arr[0]); // 解码base64
  let n = bytes.length;
  let ia = new Uint8Array(n);
  while (n--) {
    ia[n] = bytes.charCodeAt(n);
  }
  return new File([ia], fileName, {
    type: "image/jpeg"
  });
}

function SocketInit(gws) {
  if (gws && gws.ws) {
    //发送消息方法
    gws.send = function(command) {
      //首先要判断连接是否成功了
      if (!gws.openSuccessFlag && gws.ws) {
        //先执行连接
        setTimeout(() => {
          try {
            gws.ws.send(command);
          } catch (err) {
            console.error("发送消息异常", err);
          }
        }, 1000);
      } else {
        try {
          gws.ws.send(command);
        } catch (err) {
          console.error("发送消息异常", err);
        }
      }
    };

    //关闭方法
    gws.close = function() {
      if (gws.openSuccessFlag && gws.ws) {
        console.log("关闭");
        gws.ws.close();
      }
    };

    //bind事件
    gws.ws.onmessage = function(eventData) {
      console.log(eventData);
      eventData = eventData || {};

      let eventBindData = null;
      let { data } = eventData;

      //只要是消息都触发
      gws.onMessage(eventData);

      //处理消息数据
      if (gws.dataType === "json") {
        eventBindData = JSON.parse(data);
      }

      if (!eventBindData) {
        return;
      }

      //连接的心跳检测
      if (eventBindData.msg === "tick") {
        return;
      }

      //除了上述的两种情况  其他的为正常的数据交互,bind onMessage

      //读取身份证回调
      if (eventBindData.device == "IdCard") {
        gws.onReadCard(eventData);
        return;
      }

      //获取人证对比
      if (eventBindData.device == "PersonVerify") {
        gws.onWitness(eventData);
        return;
      }
      //扫描文件
      if (eventBindData.device == "HighCamera") {
        gws.onScreen(eventData);
      }
    };

    gws.ws.onopen = function() {
      //连接成功
      gws.onOpen();
      gws.openSuccessFlag = true;
    };

    //bind close事件
    gws.ws.onclose = function(eventData) {
      console.warn("连接断开");
      gws.onClose(eventData);
    };

    //通讯错误时触发
    gws.ws.onerror = function(err) {
      gws.onError(err);
    };
  }
}
